---------------------------------------------------------------
-- @Description：         read/write Memdb
---------------------------------------------------------------
local skynet = require "skynet"
require "skynet.manager"
local redis = require "skynet.db.redis"
local log = require "sky_log"
local queue = require "skynet.queue"
local Queue = queue()

local M = {
    redis_connect_t = {},
}
local default_expire_time = 3600 * 24 --一天

local function get_redis_connect(host_conf, passwd, need_auth)
    local conf = {}
    conf.host = string.match(host_conf, "(%S+):")
    conf.port = tonumber(string.match(host_conf, ":(%d+)"))
    if tonumber(need_auth)==1 and passwd then
        conf.auth = passwd
    end

    local redis_index = redis.connect(conf)
    if not redis_index then
        log.error("failed to connect redis [conf]= ", conf)
        return false
    end
        
    local ok, info = pcall(redis_index.info, redis_index, 'Server')
    if ok then
        local s, e = string.find(info, 'redis_version:')
        if s and s > 0 then
            conf.redis_version = info.sub(info, e + 1, e + 5)
            --conf.main_version = tonumber(string.sub(conf.redis_version, 1, 1))
        end
        conf.redis_index = redis_index
    end

    return conf
end

function M:connect_redis(config)
    self.redis_connect_t[tonumber(config.plat_id)] = {}
    local connect_t = self.redis_connect_t[tonumber(config.plat_id)]
    --gi
    if config.redis_gi_host then
        local connect_info = get_redis_connect(config.redis_gi_host, config.redis_gi_passwd, config.need_auth)
        connect_t.redis_gi = connect_info
    end
    --ext
    if config.redis_ext_host then
        local connect_info = get_redis_connect(config.redis_ext_host, config.redis_ext_passwd, config.need_auth)
        connect_t.redis_ext = connect_info
    end
    --lottery
    if config.redis_lottery_host then
        local connect_info = get_redis_connect(config.redis_lottery_host, config.redis_lottery_passwd, config.need_auth)
        connect_t.redis_lottery = connect_info
    end
    --tid
    if config.redis_tid_host then
        local connect_info = get_redis_connect(config.redis_tid_host, config.redis_tid_passwd, config.need_auth)
        connect_t.redis_tid = connect_info
    end
end

function M:del(redis_type, platid, key)
    local redis_index = ((self.redis_connect_t[tonumber(platid)] or {})[redis_type] or {}).redis_index
    if not redis_index then
        return false
    end

    local res = redis_index:del(key)
   
    if res~=1 then 
        return false
    end

    return true
end

function M:get(redis_type, platid, key)
    local redis_index = ((self.redis_connect_t[tonumber(platid)] or {})[redis_type] or {}).redis_index
    if not redis_index then
        return false
    end

    local res = redis_index:get(key)
    --log.info("res=", res)

    --返回是string, 需要tonumber
    return true, res
end

function M:set(redis_type, platid, key, value, expire_time)
  
    local redis_index = ((self.redis_connect_t[tonumber(platid)] or {})[redis_type] or {}).redis_index
    if not redis_index then
        return false
    end
    
    local res = redis_index:set(key, value)
    if res~="OK" then 
        return false
    end

    local expire = expire_time or default_expire_time
    redis_index:expire(key, expire)

    return true, res
end

function M:set_robot_total_lose(platid, key, value, expire_time)
    local g_ret, old_money = self:get("redis_gi", platid, key)
    if g_ret~=true then
        log.error("set_robot_total_lose error_1!")
        return
    end
    old_money = tonumber(old_money) or 0

    local new_value = old_money + tonumber(value)

    local ret = self:set("redis_gi", platid, key, new_value, expire_time)
    if not ret then
        log.error("set_robot_total_lose error_2!")
    else
        log.warning("set_robot_total_lose:", "old_money="..old_money
            .." |add_money="..value.." |new_value="..new_value.." |expire_time="..(expire_time or "nil"))
    end
end

--============================= Init =============================--
function M:init_by_config(config)
    if not tonumber(config.plat_id) then
        log.error("redis connect error: no plat_id!")
        return
    end

    self:connect_redis(config)

    local info_t = {}
    for k, v in pairs(self.redis_connect_t[tonumber(config.plat_id)]) do
        local t = {}
        t.host = v.host
        t.port = v.port
        t.redis_version = v.redis_version
        info_t[k] = t
    end

    log.warning("connect plat_id ["..config.plat_id.."] redis success=", info_t)
end

skynet.start(function ()
    skynet.dispatch("lua", function(session, address, cmd, ...)
        local f = M[cmd]
        if f then
            --skynet.ret(skynet.pack(f(M, ...)))
            skynet.ret(skynet.pack( Queue(f, M, ...) ) )
        else
            skynet.error(string.format("Unknown command %s", tostring(cmd)))
        end
    end)

    skynet.register(".redis")
end)

return M
